<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成都工业学院本科教育教学审核评估 AI 助学机器人</title>
    <script src="https://cdn.jsdelivr.net/npm/marked@4.0.0/lib/marked.min.js"></script>
    <!-- 引入 MathJax -->
    <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        .chat-header {
            background-color: #075e54;
            color: white;
            padding: 10px 20px;
            text-align: center;
            font-size: 1.2em;
        }
        #chat-container {
            flex-grow: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }
        .message {
            max-width: 70%;
            margin-bottom: 10px;
            padding: 10px 15px;
            border-radius: 20px;
            line-height: 1.4;
            word-wrap: break-word;
        }
        .user-message {
            align-self: flex-end;
            background-color: #dcf8c6;
            color: #000;
        }
        .ai-message {
            align-self: flex-start;
            background-color: #fff;
            color: #000;
        }
        .input-area {
            display: flex;
            padding: 10px;
            background-color: #f0f0f0;
        }
        #user-input {
            flex-grow: 1;
            padding: 10px;
            border: none;
            border-radius: 20px;
            margin-right: 10px;
            font-size: 16px;
        }
        #send-button {
            background-color: #075e54;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 16px;
        }
        #send-button:hover {
            background-color: #128c7e;
        }
        #clear-button {
            background-color: #ff5252;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 16px;
            margin-left: 10px;
        }
        #clear-button:hover {
            background-color: #e53935;
        }
        .loading {
            text-align: center;
            padding: 10px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="chat-header">本科教育教学审核评估AI 助学专家</div>
    <div id="chat-container"></div>
    <div class="input-area">
        <input type="text" id="user-input" placeholder="输入您的问题...">
        <button id="send-button">发送</button>
        <button id="clear-button">清除上下文</button>
    </div>

    <script>
        const chatContainer = document.getElementById('chat-container');
        const userInput = document.getElementById('user-input');
        const sendButton = document.getElementById('send-button');
        const clearButton = document.getElementById('clear-button');
        let isFirstLoad = true;

        // 等待marked加载完成
        window.onload = function() {
            showWelcomeMessage();
        };

        function showWelcomeMessage() {
            if (isFirstLoad) {
                const welcomeMessage = `你好，我是 **成都工业学院** 本科教育教学审核评估应知应会助学大模型，你可以在我这儿检验学习成果哦，比如你可以说 “我们学校校训是什么？”或者“为什么要进行应知应会学习？”。`;
                addMessage(welcomeMessage, false);
                isFirstLoad = false;
            }
        }

        function addMessage(content, isUser) {
            const messageDiv = document.createElement('div');
            messageDiv.className = isUser ? 'message user-message' : 'message ai-message';
            try {
                // 将 LaTeX 公式用 $$ 包裹起来以便 MathJax 渲染
                content = content.replace(/\((.*?)\)/g, '$$$1$$$').replace(/\[(.*?)\]/g, '$$\[$1\]$$');
                messageDiv.innerHTML = isUser ? content : marked.parse(content);
            } catch (e) {
                messageDiv.innerHTML = content;
            }
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
            // 调用 MathJax 重新渲染页面上的公式
            if (window.MathJax) {
                MathJax.typesetPromise([messageDiv]);
            } else {
                document.addEventListener("DOMContentLoaded", () => {
                    if (window.MathJax) {
                        MathJax.typesetPromise([messageDiv]);
                    }
                });
            }
        }

        function setLoading(loading) {
            const existingLoading = document.querySelector('.loading');
            if (loading && !existingLoading) {
                const loadingDiv = document.createElement('div');
                loadingDiv.className = 'loading';
                loadingDiv.textContent = '正在思考...';
                chatContainer.appendChild(loadingDiv);
                chatContainer.scrollTop = chatContainer.scrollHeight;
            } else if (!loading && existingLoading) {
                existingLoading.remove();
            }
        }

        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;

            try {
                addMessage(message, true);
                userInput.value = '';
                setLoading(true);

                const response = await fetch('/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ message: message }),
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                let aiResponse = '';
                let aiMessageDiv = null;

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = new TextDecoder().decode(value);
                    const lines = chunk.split('\n\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                aiResponse += data.content;
                                
                                if (!aiMessageDiv) {
                                    aiMessageDiv = document.createElement('div');
                                    aiMessageDiv.className = 'message ai-message';
                                    chatContainer.appendChild(aiMessageDiv);
                                }
                                
                                aiMessageDiv.innerHTML = marked.parse(aiResponse);
                                chatContainer.scrollTop = chatContainer.scrollHeight;
                                // 调用 MathJax 重新渲染页面上的公式
                                if (window.MathJax) {
                                    MathJax.typesetPromise([aiMessageDiv]);
                                } else {
                                    document.addEventListener("DOMContentLoaded", () => {
                                        if (window.MathJax) {
                                            MathJax.typesetPromise([aiMessageDiv]);
                                        }
                                    });
                                }
                            } catch (e) {
                                console.error('Error parsing JSON:', e);
                            }
                        }
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                addMessage('抱歉，发生了错误。请稍后再试。', false);
            } finally {
                setLoading(false);
            }
        }

        async function clearContext() {
            try {
                const response = await fetch('/clear_context', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                chatContainer.innerHTML = '';
                isFirstLoad = true;
                showWelcomeMessage();
            } catch (error) {
                console.error('Error clearing context:', error);
                alert('清除上下文时发生错误，请稍后重试。');
            }
        }

        // 事件监听器
        sendButton.addEventListener('click', sendMessage);
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        clearButton.addEventListener('click', clearContext);
    </script>
</body>
</html>



